package com.tools.cleanmaster.ui.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.os.Bundle;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.airbnb.lottie.LottieAnimationView;
import com.tools.ad.EntranceType;
import com.tools.ad.adscene.inner.CommonInterstitialScene;
import com.tools.ad.strategy.FunctionStrategyExecutor;
import com.tools.ad.util.GARecordUtils;
import com.tools.ad.util.StatusBarUtil;
import com.tools.cleanmaster.CleanGAConstant;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.functionpage.BgColorGradientView;
import com.tools.cleanmaster.functionpage.FunctionBatteryHandler;
import com.tools.cleanmaster.functionpage.FunctionBoosterHandler;
import com.tools.cleanmaster.functionpage.FunctionCPUCoolHandler;
import com.tools.cleanmaster.functionpage.FunctionHandler;
import com.tools.cleanmaster.functionpage.FunctionHandlerListener;
import com.tools.cleanmaster.functionpage.FunctionItem;
import com.tools.cleanmaster.store.CpuCoolSharedPrefManager;
import com.tools.cleanmaster.store.ResultPageSharedPrefManager;
import com.tools.cleanmaster.taskmain.ProcessItem;
import com.tools.cleanmaster.taskmain.TKPubApi;
import com.tools.cleanmaster.ui.base.ResultSingleActivity;
import com.tools.cleanmaster.ui.card.ui.ResultSingleCardLayout;
import com.tools.cleanmaster.ui.utils.LottieAnimationUtil;
import com.tools.cleanmaster.ui.view.LoadingInsideLayout;
import com.tools.cleanmaster.ui.view.header.HeadHelper;
import com.tools.cleanmaster.utils.MemoryUtils;

import java.util.ArrayList;
import java.util.Locale;

public class FunctionPageGuideActivity extends ResultSingleActivity implements View.OnClickListener {

    public final static String ITEM_EXTEA_FLAG = "item_extea";
    private static final int MORE_SUGGSETION = 12;
    private static final int FUNCTION_BATTERY = 13;
    private static final int FUNCTION_NORMAL_RESULT = 14;
    private static final int FUNCTION_BOOSTER = 15;
    private static final int FUNCTION_CPUTCOOL = 16;
    private static final long MAX_WAIT_FOR_ADVERT = 6000L; // 最大等待广告的时间
    private Button mBottomButton;
    private LoadingInsideLayout mLoadingProgress;
    private View mFeatureContainer;
    private View mPerfectFrameLayout;
    private LottieAnimationView mPerfectView;
    private FunctionItem mItem;
    private String btnText;
    private RelativeLayout mBgColorGradientView;
    private boolean isRealHandle = true;
    private FunctionHandler handler;
    private View viewRoot;
    private EntranceType mEntranceType;
    private EntranceType mInsetEntranceType;
    private EntranceType mFunctionEntranceType;
    private boolean hasShowResultCard = false;//是否有显示结果，如果有，则在退出的时候打点
    private boolean hasRequestFailed = false; // 是否有请求广告失败
    private boolean hasLoadedAdvert = false; // 是否已经加载插屏完广告
    private AnimatorListenerAdapter animatorListenerAdapter = new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            if (hasLoadedAdvert) {
                sendEmptyMessage(R.id.msg_show_interstitial_advert);
            } else if (hasRequestFailed) {
                sendEmptyMessage(R.id.msg_hide_perfect_view);
            } else {
                sendEmptyMessage(R.id.msg_hide_perfect_view, 2000L);
            }
        }
    };

    @Override
    protected void setCardHeadTitle() {
        if (mResultMultiCardLayout != null) {
            mResultMultiCardLayout.setHeadTitle(getString(R.string.landingpage_header_title));
        }
    }

    @Override
    protected void hideBackground() {
        mFeatureContainer.setVisibility(View.GONE);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.common_background_blue), 0);
        HeadHelper.setupMainHeader(this, R.id.main_title, R.string.function_resultpage_title)
                .hideSettingButton().setBackgroundColor();
    }

    @Override
    protected EntranceType getEntranceType() {
        return mEntranceType;
    }

    @Override
    public ResultPageType getResultPageType() {
        return ResultPageType.MultiCardPage;
    }

    @Override
    protected void setContentView(Bundle savedInstanceState) {
        setContentView(R.layout.function_page_guide_layout);
        StatusBarUtil.setTranslucent(this, 0);
        initViews();
        showProgressLoading();
        initData();
        handleTopContentData();

        GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_SHOW,
                String.format(Locale.ENGLISH, CleanGAConstant.L_HOME_FUNCTION, String.valueOf(getEntranceType().getName())));
    }

    private void initViews() {
        mBgColorGradientView = findViewById(R.id.bgcolor_gradient);
        mLoadingProgress = findViewById(R.id.loading);
        mFeatureContainer = findViewById(R.id.lp_feature_container);
        mPerfectFrameLayout = findViewById(R.id.lp_loading_card_perfect_rl);
        mPerfectView = findViewById(R.id.lp_loading_card_perfect_view);
        mBottomButton = findViewById(R.id.handler_bottom_btn);
        mBottomButton.setOnClickListener(this);
        mBottomButton.setEnabled(false);
        mBottomButton.setVisibility(View.GONE);
    }

    private void initData() {
        String sceneKey = getIntent().getStringExtra(ITEM_EXTEA_FLAG);
        mItem = FunctionItem.getItemByKey(sceneKey);
        mFeatureContainer.setVisibility(View.VISIBLE);
        if (null == mItem) {
            return;
        }

        mEntranceType = null;
        if (mItem == FunctionItem.BOOSTEROVER || mItem == FunctionItem.BOOSTER) {
            viewRoot = findViewById(R.id.function_booster);
            handler = new FunctionBoosterHandler();
            mEntranceType = EntranceType.HOME_BOOST_COMPLETED;
            mInsetEntranceType = EntranceType.HOME_BOOST_INTERSTITIAL;
            mFunctionEntranceType = EntranceType.FUNCTION_BOOST;

        } else if (mItem == FunctionItem.BATTERY || mItem == FunctionItem.BATTERYOVER) {
            viewRoot = findViewById(R.id.function_battery);
            handler = new FunctionBatteryHandler();
            mEntranceType = EntranceType.HOME_POWER_COMPLETED;
            mInsetEntranceType = EntranceType.HOME_POWER_INTERSTITIAL;
            mFunctionEntranceType = EntranceType.FUNCTION_POWER;

        } else if (mItem == FunctionItem.CPUOVER || mItem == FunctionItem.CPUCOOL) {
            viewRoot = findViewById(R.id.function_cpucool);
            handler = new FunctionCPUCoolHandler();
            mEntranceType = EntranceType.HOME_CPU_COMPLETED;
            mInsetEntranceType = EntranceType.HOME_CPU_INTERSTITIAL;
            mFunctionEntranceType = EntranceType.FUNCTION_COOL;
        }

        handler.setHandlerListener(new FunctionHandlerListener() {
            @Override
            public void startFakeScan() {
                super.startFakeScan();
                dismissProgressLoading();
            }

            @Override
            public void startScan() {
                super.startScan();
                if (mItem == FunctionItem.CPUOVER) {
                    ValueAnimator animator = ValueAnimator.ofInt(20, 45);
                    animator.setDuration(3000);
                    animator.setInterpolator(new AccelerateDecelerateInterpolator());
                    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
//                            mBgColorGradientView.setColorType(mBgColorGradientView.getColorBySize((Integer) animation.getAnimatedValue()));
                        }
                    });
                    animator.start();
                }
                dismissProgressLoading();
            }

            @Override
            public void startHandler(boolean isReal) {

                //加载插屏广告
                imContext.getAdSceneManager().load(mInsetEntranceType);

                //加载广告
                imContext.getAdSceneManager().load(mEntranceType);

                isRealHandle = isReal;
                mBottomButton.setEnabled(false);
                if (mItem == FunctionItem.CPUOVER) {
                    mBgColorGradientView.clearAnimation();
                    ValueAnimator animator = ValueAnimator.ofInt(45, 20);
                    animator.setDuration(1500);
                    animator.setInterpolator(new AccelerateDecelerateInterpolator());
                    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                           // mBgColorGradientView.setColorType(mBgColorGradientView.getColorBySize((Integer) animation.getAnimatedValue()));
                        }
                    });
                    animator.start();
                    mBottomButton.setVisibility(View.GONE);
                } else if (mItem == FunctionItem.BATTERYOVER) {
                    mBottomButton.setText(R.string.function_battery_bottom_btn);
                }
                super.startHandler(isReal);
            }

            @Override
            public void finishScan() {
                super.finishScan();
                mBgColorGradientView.clearAnimation();
                mBottomButton.setVisibility(View.VISIBLE);
                mBottomButton.setEnabled(true);
               // mBgColorGradientView.startGradient(BgColorGradientView.GradientColorType.NORMAL, 1000L, null);

                hasShowResultCard = true;
            }

            @Override
            public void finishHandler() {
                super.finishHandler();

                if (FunctionItem.isOverByItem(mItem)) {
                    mBottomButton.setVisibility(View.GONE);
                    sendEmptyMessage(R.id.msg_cleaner_home_func_item_show_result_delay, 1000);
                } else {
                    sendEmptyMessage(R.id.msg_cleaner_home_func_item_show_result_delay);
                }
            }

            @Override
            public void showAppsDetailPage() {
                super.showAppsDetailPage();
                mBottomButton.setVisibility(View.GONE);
            }
        });

        handler.init(imContext, viewRoot);
        if (FunctionItem.isOverByItem(mItem)) {
            //正常扫描，依次回调 startScan() 、finishScan()、showAppsDetailPage()
            //点击清理按钮后，依次回调 startHandler()、finishHandler()
            handler.startStateScan();
        } else {
            //加载广告
            imContext.getAdSceneManager().load(mEntranceType);
            //正常状态假扫描，只会回调 startScan() 、finishHandler()
            handler.startStateFakeHandler();
        }
    }

    @Override
    public void subHandleMessage(Message msg) {
        super.subHandleMessage(msg);
        if (msg.what == R.id.msg_ad_common_scene_loaded) {
            if (mResultSingleCardLayout != null && mResultSingleCardLayout.getVisibility() == View.VISIBLE) {
                //单卡片结果页
                mAdView = imContext.getAdSceneManager().getAdScene(mEntranceType).getAdView();
                ViewGroup adLayout = mResultSingleCardLayout.findViewById(R.id.advert_container);
                adLayout.setVisibility(View.VISIBLE);
                adLayout.removeAllViews();
                adLayout.addView(mAdView);

            } else if (mCardListAdapter != null) {
                //多卡片结果页
                mCardListAdapter.notifyDataSetChanged();
            }
            msg.arg1 = R.id.msg_mob_message_end;
        } else if (msg.what == R.id.msg_cleaner_home_func_item_show_result_delay) {
            mBgColorGradientView.clearAnimation();
            handleTopContentData();
            completeAction();
            if (FunctionItem.isOverByItem(mItem)) {
                changeTitle(FUNCTION_NORMAL_RESULT);
            } else {
                changeTitle(MORE_SUGGSETION);
            }
        } else if (msg.what == R.id.msg_show_complete_view) {

            completeAction();
        } else if (msg.what == R.id.msg_show_interstitial_advert) {
            //显示插屏广告数据
            CommonInterstitialScene interstitialScene = (CommonInterstitialScene) mInsetEntranceType.getAdScene();
            if (interstitialScene != null) {
                interstitialScene.showAd();
            }
        } else if (msg.what == R.id.msg_hide_perfect_view) {
            sendEmptyMessage(R.id.msg_show_interstitial_advert, 500L);
            showResultCard();
        } else if (msg.what == R.id.msg_ad_interstitial_loaded) {
            hasLoadedAdvert = true;
        } else if (msg.what == R.id.msg_ad_interstitial_closed) {
            showResultCard();
        } else if (msg.what == R.id.msg_ad_interstitial_failed) {
            hasRequestFailed = true;
        }
    }

    private void handleTopContentData() {
        switch (mItem) {
            case BATTERY:
                ArrayList<ProcessItem> list = TKPubApi.getRunningProcesses(getApplication(), true);
                resultPageData.putInt(ResultSingleCardLayout.ICON_ID, R.drawable.speed_icon);
                resultPageData.putInt(ResultSingleCardLayout.BG_ID, R.drawable.new_res_battery);
                resultPageData.putInt(ResultSingleCardLayout.APPS_COUNT, list.size());
                btnText = getString(R.string.function_battery_button);
                changeTitle(FUNCTION_BATTERY);
                break;
            case BATTERYOVER:
                resultPageData.putBoolean(ResultSingleCardLayout.IS_REAL_HANDLE, isRealHandle);
                ArrayList<ProcessItem> lists = TKPubApi.getRunningProcesses(getApplication(), true);
                resultPageData.putInt(ResultSingleCardLayout.ICON_ID, R.drawable.speed_icon);
                resultPageData.putInt(ResultSingleCardLayout.BG_ID, R.drawable.new_res_battery);
                resultPageData.putInt(ResultSingleCardLayout.APPS_COUNT, lists.size());
                btnText = getString(R.string.function_battery_button);
                changeTitle(FUNCTION_BATTERY);
                break;
            case BOOSTER:
                ArrayList<ProcessItem> processlist1 = TKPubApi.getRunningProcesses(getApplication(), true);
                long memerySize1 = MemoryUtils.getAvailableRam(this, processlist1);
                resultPageData.putInt(ResultSingleCardLayout.ICON_ID, R.drawable.rocket);
                resultPageData.putInt(ResultSingleCardLayout.BG_ID, R.drawable.new_res_mount);
                resultPageData.putLong(ResultSingleCardLayout.MEM_COUNT, memerySize1);
                btnText = getString(R.string.recommend_card_booster_btn_text);
                changeTitle(FUNCTION_BOOSTER);
                break;
            case BOOSTEROVER:
                ArrayList<ProcessItem> processlist = TKPubApi.getRunningProcesses(getApplication(), true);
                long memerySize = MemoryUtils.getAvailableRam(this, processlist);
                resultPageData.putInt(ResultSingleCardLayout.ICON_ID, R.drawable.rocket);
                resultPageData.putInt(ResultSingleCardLayout.BG_ID, R.drawable.new_res_mount);
                resultPageData.putLong(ResultSingleCardLayout.MEM_COUNT, memerySize);
                btnText = getString(R.string.recommend_card_booster_btn_text);
                changeTitle(FUNCTION_BOOSTER);
                break;
            case CPUCOOL:
            case CPUOVER:
                resultPageData.putBoolean(ResultSingleCardLayout.IS_REAL_HANDLE, isRealHandle);
                resultPageData.putInt(ResultSingleCardLayout.ICON_ID, R.drawable.cup_cool_icon);
                resultPageData.putInt(ResultSingleCardLayout.BG_ID, R.drawable.new_res_ice);
                resultPageData.putInt(ResultSingleCardLayout.COOL_COUNT, CpuCoolSharedPrefManager.getCpuCoolLastTempDrop());
                btnText = getString(R.string.cpu_cool_down_button_msg);
                changeTitle(FUNCTION_CPUTCOOL);
                break;
        }
        mBottomButton.setText(Html.fromHtml(btnText));
    }

    private void disPlayPerfectView() {
     //   mBgColorGradientView.startGradient(BgColorGradientView.GradientColorType.NORMAL, 1000L, null);

        mPerfectFrameLayout.setVisibility(View.VISIBLE);
        mPerfectView.addAnimatorListener(animatorListenerAdapter);
        LottieAnimationUtil.loadLottieAnimation(this, mPerfectView, "function_complete", true);
    }

    private void showResultCard() {
        switch (getResultPageType()) {
            case MultiCardPage:
                startMultiCardAnim();
                break;
            case SingleCardPage:
                mFeatureContainer.setVisibility(View.GONE);
                mPerfectView.setVisibility(View.GONE);
                mPerfectFrameLayout.setVisibility(View.GONE);
                startSingleCardFunctionItemAnim(mItem, resultPageData);
                break;
            default:
                break;
        }

        new FunctionStrategyExecutor(imContext, imContext.getADModule(), mFunctionEntranceType.getName()).record();
    }

    private void completeAction() {
        mFeatureContainer.setVisibility(View.GONE);
        mBottomButton.setEnabled(false);
        disPlayPerfectView();
    }

    private void showProgressLoading() {
        mLoadingProgress.setVisibility(View.VISIBLE);
    }

    private void dismissProgressLoading() {
        mLoadingProgress.setVisibility(View.GONE);
    }

    private void changeTitle(int status) {
        switch (status) {
            case MORE_SUGGSETION:
                if (ResultPageSharedPrefManager.isCloudResultPageSwitch(this)) {
                    HeadHelper.setupMainHeader(this, R.id.main_title, R.string.landing_page_title_optimized).hideSettingButton();
                } else {
                    HeadHelper.setupMainHeader(this, R.id.main_title, R.string.landing_page_title_suggestion).hideSettingButton();
                }
                break;
            case FUNCTION_BATTERY:
                HeadHelper.setupMainHeader(this, R.id.main_title, R.string.function_battery_icon_text).hideSettingButton();
                break;
            case FUNCTION_NORMAL_RESULT:
                HeadHelper.setupMainHeader(this, R.id.main_title, R.string.function_resultpage_title)
                        .hideSettingButton();
                break;
            case FUNCTION_BOOSTER:
                HeadHelper.setupMainHeader(this, R.id.main_title, R.string.function_booster_icon_text)
                        .hideSettingButton();
                break;
            case FUNCTION_CPUTCOOL:
                HeadHelper.setupMainHeader(this, R.id.main_title, R.string.function_cpucool_icon_text)
                        .hideSettingButton();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        //避免消息
        removeEmptyMessage(R.id.msg_ad_interstitial_failed);
        removeEmptyMessage(R.id.msg_ad_interstitial_loaded);
        removeEmptyMessage(R.id.msg_ad_interstitial_closed);

        super.onDestroy();
        if (handler != null) {
            handler.onDestroyView();
        }
        handler = null;
        viewRoot = null;
        dismissProgressLoading();
        imContext.getAdSceneManager().release(mEntranceType);

        if (hasShowResultCard) {
            GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_FINISH,
                    String.format(Locale.ENGLISH, CleanGAConstant.L_FUNCTION, String.valueOf(mEntranceType.getName())));
        }
    }

    @Override
    public void onBackPressed() {
        if (handler != null) {
            handler.onDestroyView();
        }
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        if (handler != null) {
            GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_CLICK,
                    String.format(Locale.ENGLISH, CleanGAConstant.L_FUNCTION_BOTTOM_CLICK, String.valueOf(mEntranceType.getName())));
            handler.startStateHandler();
        }
    }
}
